package com.nc.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nc.user.tool.tool.EDcrypionUtils;
import com.plug.BeanUtil;
import com.plug.result.ReqPage;
import com.plug.result.RetResponse;
import com.plug.result.RetResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import com.nc.user.dao.FrmRoleDao;
import com.nc.user.dao.FrmUsersDao;
import com.nc.user.model.dto.UserDto;
import com.nc.user.model.entity.FrmRole;
import com.nc.user.model.entity.FrmUsers;
import com.nc.user.service.AdminUsersService;

import java.util.LinkedList;
import java.util.Optional;

/**
 * 创建人:    xvzhe
 * 创建时间:
 * 修改时间:
 * 版本:      v1.0
 */
@Service
public class AdminUsersServiceImpl implements AdminUsersService {
    @Autowired
    private FrmRoleDao frmRoleDao;
    @Autowired
    private FrmUsersDao frmUsersDao;

    @Override
    public RetResult save(UserDto userDto) {
        FrmUsers frmUsers = BeanUtil.convertToBean(userDto, FrmUsers.class);
        if (StringUtils.isNotBlank(frmUsers.getId())) {

        }
        frmUsers.setPassword(EDcrypionUtils.shiroPassword(frmUsers.getPassword()));
        if (userDto.getRoleCode() != null && userDto.getRoleCode().size() != 0) {
            frmUsers.setFrmRoles(frmRoleDao.findByCodeIn(userDto.getRoleCode()));
        }
        frmUsersDao.save(frmUsers);
        return RetResponse.makeOKRsp();
    }

    @Override
    public RetResult findPage(ReqPage reqPage) {
        JSONObject req = Optional.ofNullable(reqPage.getCommon()).orElseGet(JSONObject::new);
        FrmUsers entity = JSON.parseObject(req.toJSONString(), FrmUsers.class);
        int page = reqPage.getPage() - 1;
        int size = reqPage.getLimit();
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "modifiedTime");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<FrmUsers> example = Example.of(entity, matcher);
        Page<FrmUsers> pages = frmUsersDao.findAll(example, pageable);
        return RetResponse.makeRsp(0, "成功", pages.getContent(), (int) pages.getTotalElements());
    }
}
